var BASE_URL = "/KindlePush/";
var FINIHSED = false;
$(document).ready(function(){
    $("#x-btn-more-settings").toggle(function(){
        $(".x-more-settings").slideDown();
        $("#x-btn-more-settings>span").text("隐藏设置 «");
        return false;
    },function(){
        $(".x-more-settings").slideUp();
        $("#x-btn-more-settings>span").text("更多设置 »");
        return false;
    });

    $("#x-btn-push-kindle").click(function(){
        $('#myModal').modal();
        $('#myModal').on('hidden', function () {
        	if(!FINIHSED){
	        	$.ajax({
	            	method:"GET",
	    			url: BASE_URL+"forum/cancel"
	    		});
	        	FINIHSED = true;
        	}
        });
        
        var url = $("#input-url").val();
        var email = $("#input-email").val();
        var domain = $("#input-domain").val();
        var bookType = $("#input-bookType").val();
        FINIHSED = false;
        $("#push-close").text("取消推送");
        
        $.ajax({
        	method:"GET",
			url: BASE_URL+"forum/push?url="+url+"&email="+(email?email+domain:"")+"&bookType="+bookType 
		});
        
        var progressFun = function(){
        	 $.ajax({
             	method:"GET",
     			url: BASE_URL+"forum/progress",
     			dataType:"json",
     			success:function(data){
     				var progress = parseInt(data.progress);
     				var msg = data.msg;
     				$("#push-progress").css("width",progress+"%");
     				$("#push-message").text(msg);
     				if(progress<100){
     					setTimeout(progressFun, 500);
     				}else{
     					FINIHSED = true;
     					$("#push-close").text("完成");
     				}
     			},
     			error: function(){
     				setTimeout(progressFun, 500);
     			}
             });
        };
        
        progressFun();
        return false;
    });
    
    //当输入URL失去焦点时触发，检查URL是否支持
    $("#input-url").blur(function(){
    	var val = this.value;
    	var help = $("#input-url+.help-inline");
    	if(val){
    		help.text("正在检测是否支持，请稍后...");
    		$.ajax({
    			method:"GET",
    			dataType:"json",
    			url: BASE_URL+"forum/topic?url="+val,
    			success:function(data){
    				help.text(data.title+"("+data.pageUrls.length+"页)");
    			},
    			error:function(err){
    				help.text("抱歉，当前输入的论坛地址无法解析，请稍后再试！！");
    			}
    		});
    	}else{
    		help.text("请输入论坛帖子的地址。");
    	}
    });
});